package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"novel/model/cache"
	"novel/model/mysql"
	"time"

	"novel/novelrpc/internal/svc"
	"novel/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CommentListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCommentListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CommentListLogic {
	return &CommentListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 小说评价展示
func (l *CommentListLogic) CommentList(in *novelrpc.CommentListRequest) (*novelrpc.CommentListResponse, error) {
	// todo: add your logic here and delete this line

	var book mysql.Book
	mysql.DB.Where("id=?", in.BookId).Find(&book)
	if book.ID == 0 {
		return nil, fmt.Errorf("该小说不存在")
	}
	var comment []mysql.CommentList
	key := fmt.Sprintf("List_%d", in.BookId)
	conunt, _ := cache.Rdb.Get(l.ctx, key).Result()
	if conunt == "" {

		tx := mysql.DB.Table("comments").
			Select("comments.*,books.title,books.text").
			Joins("LEFT JOIN books ON books.id = comments.book_id").
			Joins("LEFT JOIN users ON users.id = comments.user_id").
			Where("books.id = ?", in.BookId)
		tx.Find(&comment)
		LikeJson, _ := json.Marshal(comment)
		cache.Rdb.Set(l.ctx, key, LikeJson, time.Minute*15)
	} else {
		json.Unmarshal([]byte(conunt), &comment)
	}

	var commentList []*novelrpc.CommentList

	for _, m := range comment {
		list := novelrpc.CommentList{
			NickName: m.NickName,
			BookId:   m.BookId,
			ConText:  m.ConText,
			Title:    m.Title,
			Text:     m.Text,
		}
		commentList = append(commentList, &list)
	}
	return &novelrpc.CommentListResponse{
		List: commentList,
	}, nil
}
